package com.cloudbroker.bcs.common.configure;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.cloudbroker.bcs.common.context.RuntimeContext;

public class HSBCSConfigPlaceholderConfigure extends PropertyPlaceholderConfigurer {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(HSBCSConfigPlaceholderConfigure.class);
    
    protected boolean configLoaderChecked = false;
    
    protected void checkConfigLoaded() {
        if (!configLoaderChecked) {
            configLoaderChecked = true;
            try {
                RuntimeContext.getBean(ConfigUtil.class);
            } catch (NoSuchBeanDefinitionException e) {
                LOGGER.warn("no bean of " + ConfigUtil.class.getName() + " defined, try "
                        + HSBCSZooKeeperConfigLoader.class.getName());
                try {
                    RuntimeContext.getBean(HSBCSZooKeeperConfigLoader.class);
                } catch (NoSuchBeanDefinitionException ex) {
                    LOGGER.warn("no bean of " + HSBCSZooKeeperConfigLoader.class.getName()
                            + " defined, config might be missing");
                }
            }
        }
    }
    
    @Override
    protected String resolvePlaceholder(String placeholder, Properties props) {
        checkConfigLoaded();
        return ConfigUtil.getString(placeholder, null);
    }
    
}
